package com.chezai.client.global.location.rx;

import android.Manifest;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.util.Log;

import com.chezai.client.global.Const;
import com.chezai.client.global.TerminalApplication;
import com.chezai.client.utils.PreferenceManager;

import io.reactivex.Observer;

public class LocationObservable extends InitialValueObservable<Location> {
    private final LocationManager lm;

    public LocationObservable(LocationManager lm) {
        this.lm = lm;
    }

    @Override
    protected void subscribeListener(Observer<? super Location> observer) {
        Listener listener = new Listener(lm, observer);
        observer.onSubscribe(listener);
        Log.e("Test", "subscribeListener: 已订阅");
        if (ActivityCompat.checkSelfPermission(TerminalApplication.mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(TerminalApplication.mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            Log.e("Test", "subscribeListener: 没有定位权限");
            observer.onError(new RuntimeException("no gps location"));
            return;
        }
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 0, listener);
    }

    @Override
    protected Location getInitialValue() {
        Location loc = new Location(Const.INIT_PROVIDER);
        double lat = Double.valueOf(PreferenceManager.getString(Const.SP_BEST_LAT, "0"));
        double lon = Double.valueOf(PreferenceManager.getString(Const.SP_BEST_LON, "0"));
        loc.setLatitude(lat);
        loc.setLongitude(lon);
        return loc;
    }

    final static class Listener extends MainThreadDisposable implements LocationListener {
        private final LocationManager lm;
        private final Observer<? super Location> observer;

        Listener(LocationManager lm, Observer<? super Location> observer) {
            this.lm = lm;
            this.observer = observer;
        }

        @Override
        public void onLocationChanged(Location location) {
            if (!isDisposed()) {
                observer.onNext(location);
            }
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }

        @Override
        protected void onDispose() {
            if (isDisposed()) {
                lm.removeUpdates(this);
            }
        }
    }
}
